#include "main.h"

extern void CenterOnScreen(HWND hWnd);

/* 
 * dlgConnectProc
 * - Message handler for connect dialog
 */
BOOL CALLBACK dlgConnectProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
	case WM_INITDIALOG:
		/*
		 * Center window on screen and set default port
		 */
		CenterOnScreen(hWnd);
		SetDlgItemInt(hWnd, IDC_SERVERPORT, 7654, FALSE);
		break;

	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case IDCANCEL:
			/*
			 * Close dialog
			 */
			SendMessage(hWnd, WM_CLOSE, 0, 0);
			break;

		case IDOK:
			/*
			 * Verify valid port entered
			 */
			int nPort = GetDlgItemInt(hWnd, IDC_SERVERPORT, NULL, FALSE);
			if (nPort <= 0)
			{
				MessageBox(hWnd, "You must fill in a valid port.", "Error", MB_ICONERROR | MB_OK);
				return TRUE;
			}

			/*
			 * Verify valid IP entered
			 * - IPM_GETADDRESS returns # of areas filled out. Should be 4 ;-)
			 */
			HWND hIpControl = GetDlgItem(hWnd, IDC_SERVERIP);
			DWORD dwIPVal = NULL;
			int nFilled = SendMessage(hIpControl, IPM_GETADDRESS, 0, (LPARAM)&dwIPVal);
			if (nFilled < 4)
			{
				MessageBox(hWnd, "You must fill in a valid IP address.", "Error", MB_ICONERROR | MB_OK);
				return TRUE;
			}
			
			/*
			 * Confusing? Yea...Basically: Get each part of IP Address
			 * from control. Then use gethostbyaddr() to get info about that
			 * ip. Then fill in the server info. Complicated. Look up
			 * "Johnnie's Winsock Tutorial" for more information on how the serverInfo
			 * works! =)
			 */
			in_addr iaIP;
			iaIP.S_un.S_un_b.s_b1 = (u_char)FIRST_IPADDRESS(dwIPVal);
			iaIP.S_un.S_un_b.s_b2 = (u_char)SECOND_IPADDRESS(dwIPVal);
			iaIP.S_un.S_un_b.s_b3 = (u_char)THIRD_IPADDRESS(dwIPVal);
			iaIP.S_un.S_un_b.s_b4 = (u_char)FOURTH_IPADDRESS(dwIPVal);

			LPHOSTENT hostEntry = gethostbyaddr((const char*)&iaIP, sizeof(struct in_addr), AF_INET);

			SOCKADDR_IN *serverInfo = (SOCKADDR_IN *)malloc(sizeof(SOCKADDR_IN));
			serverInfo->sin_family = AF_INET;
			serverInfo->sin_port = htons(nPort);
			serverInfo->sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);

			/*
			 * End dialog with serverInfo returning
			 */
			EndDialog(hWnd, (int)serverInfo);
			break;
		}
		break;

	case WM_CLOSE:
		/*
		 * End dialog with 0 return (cancel)
		 */
		EndDialog(hWnd, 0);
		break;

	default:
		return FALSE;
	}
	return TRUE;
}